"""
Copyright (c) 2022 Huawei Technologies Co.,Ltd.

openGauss is licensed under Mulan PSL v2.
You can use this software according to the terms and conditions of the Mulan PSL v2.
You may obtain a copy of Mulan PSL v2 at:

          http://license.coscl.org.cn/MulanPSL2

THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
See the Mulan PSL v2 for more details.
"""
"""
Case Type   : fixed
Case Name   : jdbc驱动连接数据库，支持fixed类型相关操作
Create At   : 2023/02/27
Owner       : @li-xin12345
Description :
    1. 创建兼容B库，检查dolphin插件
    2. 远程复制java脚本至指定主机
    3. 编译java工具
    4. 运行java脚本
    5. 清理环境
Expect      :
    1. 创建成功，插件自动加载
    2. 成功
    3. 成功
    4. 成功
    5. 成功
History     :
    modified by @li-xin12345 at 2023/4/4，优化用例
"""

import os
import unittest

from yat.test import Node
from yat.test import macro
from testcase.utils.Logger import Logger
from testcase.utils.Common import Common
from testcase.utils.CommonSH import CommonSH
from testcase.utils.Constant import Constant


class JdbcSupportsFixed(unittest.TestCase):

    def setUp(self):
        self.log = Logger()
        self.log.info(f"-----{os.path.basename(__file__)} start-----")
        self.common = Common()
        self.constant = Constant()
        self.pri_user = Node(node='PrimaryDbUser')
        self.pri_root = Node(node='PrimaryRoot')
        self.pri_sh = CommonSH('PrimaryDbUser')
        self.dest_path = os.path.join(macro.DB_MY_PATH,
                                      'fixed_test').replace('\\', '/')
        self.db_name = 'db_fixed_045'
        self.java_name = "datatype_fixed_case0045"

    def test_fixed(self):
        text = '-----step1:创建兼容B库，检查dolphin插件;expect:创建成功-----'
        self.log.info(text)
        sql_cmd = f"drop database if exists {self.db_name};" \
                  f"create database {self.db_name} " \
                  f"dbcompatibility ='B';"
        self.log.info(sql_cmd)
        sql_res = self.pri_sh.execut_db_sql(sql_cmd, dbname='postgres')
        self.log.info(sql_res)
        self.assertIn(self.constant.CREATE_DATABASE_SUCCESS, sql_res,
                      '执行失败' + text)

        sql_cmd = "select extname from pg_extension where extname ='dolphin';"
        self.log.info(sql_cmd)
        sql_res = self.pri_sh.execut_db_sql(sql_cmd,
                                            dbname=self.db_name)
        self.log.info(sql_res)
        self.assertIn('dolphin', sql_res, '查询失败')

        self.log.info('-----step2:远程复制java脚本至指定主机;expect:成功-----')
        self.common.scp_file(self.pri_root,
                             f"{self.java_name}.java", self.dest_path)
        cmd = f'ls {self.dest_path}'
        res = self.pri_root.sh(cmd).result()
        self.assertIn(self.java_name, res, 'step1执行失败')

        self.log.info('-----step3:编译java工具;expect:成功-----')
        self.pri_root.scp_put(macro.JDBC_PATH,
                                          f"{self.dest_path}/postgresql.jar")
        cmd = f"javac -encoding utf-8 -cp " \
            f"{os.path.join(self.dest_path, 'postgresql.jar')} " \
            f"{os.path.join(self.dest_path, f'{self.java_name}.java')}"
        self.log.info(cmd)
        result = self.pri_root.sh(cmd).result()
        self.log.info(result)
        self.assertEqual('', result, 'step2执行失败')

        self.log.info('-----step4:运行java脚本;expect:成功-----')
        url_host_port = f"{self.pri_user.db_host}:{self.pri_user.db_port}"
        cmd = f" java -cp {os.path.join(self.dest_path, 'postgresql.jar')}" \
            f":{self.dest_path} " \
            f"{self.java_name} {url_host_port} {self.db_name} " \
            f"{self.pri_user.db_user} {self.pri_user.db_password}"
        self.log.info(cmd)
        res = self.common.get_sh_result(self.pri_root, cmd)
        self.log.info(res)
        self.assertIn('col1 = 123.12', res, "执行失败")
        self.assertIn('col2 = 6', res, "执行失败")

    def tearDown(self):
        self.log.info('----step4:清理环境;expect:成功----')
        self.log.info('----清理编译脚本----')
        cmd = f'rm -rf {self.dest_path};' \
              f'if [ -d {self.dest_path} ]; ' \
              f'then echo "exists"; else echo "not exists"; fi'
        self.log.info(cmd)
        res = self.common.get_sh_result(self.pri_root, cmd)
        self.log.info(res)
        self.log.info('----删除库----')
        sql_res = self.pri_sh.execut_db_sql(
            f"drop database if exists {self.db_name};", dbname='postgres')
        self.log.info(sql_res)
        self.assertEqual('not exists', res, "清理编译脚本失败")
        self.assertIn(self.constant.DROP_DATABASE_SUCCESS, sql_res,
                      "删库失败")
        self.log.info(f"-----{os.path.basename(__file__)} end-----")
